//
//  RouterViewController.swift
//  TestIos
//
//  Created by liyadong on 2025/11/11.
//  Copyright © 2025 Liyadong. All rights reserved.
//

import UIKit
import SnapKit

@objc(RouterViewController)
class RouterViewController: UIViewController {
    
    private struct RouterDemoItem {
        let title: String
        let description: String
        let action: () -> Void
    }
    
    private var tableView: UITableView!
    private var dataArray: [RouterDemoItem] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = "Router 调试"
        self.view.backgroundColor = UIColor.white
        
        // 设置UI
        setupUI()
        
        // 准备数据
        prepareData()
    }
    
    // MARK: - UI设置
    private func setupUI() {
        tableView = UITableView(frame: .zero, style: .grouped)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
        view.addSubview(tableView)
        
        tableView.snp.makeConstraints { make in
            make.top.equalTo(view.safeAreaLayoutGuide)
            make.leading.trailing.bottom.equalToSuperview()
        }
    }
    
    // MARK: - 数据准备
    private func prepareData() {
        dataArray = [
            RouterDemoItem(
                title: "基础路由跳转",
                description: "最简单的路由跳转，无参数",
                action: { [weak self] in
                    NHTRouter.open(NHTRouterURL.settings)
                }
            ),
            RouterDemoItem(
                title: "带参数的路由跳转",
                description: "URL中包含参数 :userId",
                action: { [weak self] in
                    NHTRouter.open("nht://user/12345")
                }
            ),
            RouterDemoItem(
                title: "带多个参数的路由跳转",
                description: "URL中包含多个参数 :productId 和 :category",
                action: { [weak self] in
                    NHTRouter.open("nht://product/67890/electronics")
                }
            ),
            RouterDemoItem(
                title: "带Query参数的路由跳转",
                description: "使用URL Query参数传递数据",
                action: { [weak self] in
                    NHTRouter.open("nht://search?keyword=iPhone&type=product&page=1")
                }
            ),
            RouterDemoItem(
                title: "带UserInfo的路由跳转",
                description: "通过userInfo传递额外参数",
                action: { [weak self] in
                    let userInfo = [
                        "source": "homepage",
                        "timestamp": Date().timeIntervalSince1970,
                        "extra": "额外信息"
                    ] as [String : Any]
                    NHTRouter.open("nht://user/99999?name=张三", userInfo, nil)
                }
            ),
            RouterDemoItem(
                title: "带Completion回调的路由跳转",
                description: "路由跳转完成后执行回调",
                action: { [weak self] in
                    NHTRouter.open(NHTRouterURL.settings) { result in
                        let alert = UIAlertController(
                            title: "路由完成",
                            message: "设置页面已打开，回调已执行",
                            preferredStyle: .alert
                        )
                        print("打开路由回调已经完成=============++++++++")
                        
                        alert.addAction(UIAlertAction(title: "确定", style: .default))
                        self?.present(alert, animated: true)
                    }
                }
            ),
            RouterDemoItem(
                title: "使用ObjectHandler获取对象",
                description: "通过路由获取数据对象",
                action: { [weak self] in
                    if let userData = NHTRouter.object("nht://api/user/12345") as? [String: Any] {
                        let message = """
                        获取到的用户数据：
                        ID: \(userData["userId"] ?? "")
                        用户名: \(userData["userName"] ?? "")
                        头像: \(userData["avatar"] ?? "")
                        """
                        let alert = UIAlertController(
                            title: "获取对象成功",
                            message: message,
                            preferredStyle: .alert
                        )
                        alert.addAction(UIAlertAction(title: "确定", style: .default))
                        self?.present(alert, animated: true)
                    }
                }
            ),
            RouterDemoItem(
                title: "检查URL是否可以打开",
                description: "使用canOpen检查路由是否已注册",
                action: { [weak self] in
                    let url1 = NHTRouterURL.settings
                    let url2 = "nht://unknown/page"
                    
                    let canOpen1 = NHTRouter.canOpen(url: url1)
                    let canOpen2 = NHTRouter.canOpen(url: url2)
                    
                    let message = """
                    \(url1): \(canOpen1 ? "可以打开" : "无法打开")
                    \(url2): \(canOpen2 ? "可以打开" : "无法打开")
                    """
                    
                    let alert = UIAlertController(
                        title: "URL检查结果",
                        message: message,
                        preferredStyle: .alert
                    )
                    alert.addAction(UIAlertAction(title: "确定", style: .default))
                    self?.present(alert, animated: true)
                }
            ),
            RouterDemoItem(
                title: "生成URL",
                description: "使用generateURL根据pattern和参数生成URL",
                action: { [weak self] in
                    if let generatedURL = NHTRouter.generateURL(NHTRouterURL.userDetail, ["88888"]) {
                        let message = "生成的URL: \(generatedURL)"
                        let alert = UIAlertController(
                            title: "URL生成",
                            message: message,
                            preferredStyle: .alert
                        )
                        alert.addAction(UIAlertAction(title: "确定", style: .default))
                        self?.present(alert, animated: true)
                        
                        // 使用生成的URL进行跳转
                        DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
                            NHTRouter.open(generatedURL)
                        }
                    }
                }
            ),
            RouterDemoItem(
                title: "通配符路由",
                description: "使用通配符 ~ 匹配任意路径",
                action: { [weak self] in
                    NHTRouter.open("nht://wildcard/any/path/here")
                }
            ),
            RouterDemoItem(
                title: "组合场景：参数+Query+UserInfo+Completion",
                description: "展示路由的所有功能组合使用",
                action: { [weak self] in
                    let userInfo = [
                        "from": "demo",
                        "action": "test"
                    ] as [String : Any]
                    
                    NHTRouter.open(
                        "nht://user/77777?name=李四&age=25",
                        userInfo
                    ) { result in
                        print("路由完成，返回结果: \(String(describing: result))")
                    }
                }
            )
        ]
    }
}

// MARK: - UITableViewDataSource & UITableViewDelegate
extension RouterViewController: UITableViewDataSource, UITableViewDelegate {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        
        let item = dataArray[indexPath.row]
        cell.textLabel?.text = item.title
        cell.textLabel?.numberOfLines = 0
        cell.detailTextLabel?.text = item.description
        cell.detailTextLabel?.numberOfLines = 0
        cell.detailTextLabel?.textColor = .gray
        cell.accessoryType = .disclosureIndicator
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        let item = dataArray[indexPath.row]
        item.action()
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        return 80
    }
}
